'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { toast } from 'react-toastify';
import './LoginModal.css';

// 用户登录参数接口
interface LoginFormData {
    username: string;
    password: string;
    remember: boolean;
    phone: string;
    code: string;
    agreeTerms: boolean;
}

interface LoginModalProps {
    visible: boolean;
    onClose: () => void;
    onLoginSuccess?: () => void;
    login: (credentials: {username: string; password: string}) => Promise<boolean>;
    phoneLogin: (credentials: {phone: string; code: string}) => Promise<boolean>;
}

export default function LoginModal({
                                       visible,
                                       onClose,
                                       onLoginSuccess,
                                       login,
                                       phoneLogin
                                   }: LoginModalProps) {
    // 登录表单数据
    const [formData, setFormData] = useState<LoginFormData>({
        username: '',
        password: '',
        remember: false,
        phone: '',
        code: '',
        agreeTerms: false
    });

    // 登录方式切换：password-账号密码，phone-手机号验证码
    const [loginMethod, setLoginMethod] = useState<'password' | 'phone'>('password');

    // 验证码倒计时
    const [countdown, setCountdown] = useState<number>(0);

    // 当弹窗关闭时重置表单
    useEffect(() => {
        if (!visible) {
            resetForm();
        }
    }, [visible]);

    // 重置表单
    const resetForm = () => {
        setFormData({
            username: '',
            password: '',
            remember: false,
            phone: '',
            code: '',
            agreeTerms: false
        });
        setLoginMethod('password');
        setCountdown(0);
    };

    // 处理表单输入变化
    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value, type, checked } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: type === 'checkbox' ? checked : value
        }));
    };

    // 切换登录方式
    const toggleLoginMethod = (method: 'password' | 'phone') => {
        setLoginMethod(method);
        // 清空当前表单数据
        if (method === 'password') {
            setFormData(prev => ({ ...prev, phone: '', code: '' }));
        } else {
            setFormData(prev => ({ ...prev, username: '', password: '' }));
        }
        setCountdown(0);
    };

    // 获取验证码
    const getVerificationCode = () => {
        // 简单验证手机号格式
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (!phoneRegex.test(formData.phone)) {
            toast.error('请输入有效的手机号', {
                position: "top-center",
                autoClose: 2000,
                theme: 'colored',
            });
            return;
        }

        // 模拟发送验证码
        toast.success('验证码已发送，请注意查收', {
            position: "top-center",
            autoClose: 2000,
            theme: 'colored',
        });

        // 开始倒计时
        setCountdown(60);
        const timer = setInterval(() => {
            setCountdown(prev => {
                if (prev <= 1) {
                    clearInterval(timer);
                    return 0;
                }
                return prev - 1;
            });
        }, 1000);

        return () => clearInterval(timer);
    };

    // 处理账号密码登录提交
    const handlePasswordLogin = async (e: React.FormEvent) => {
        e.preventDefault();

        try {
            if (!formData.username) {
                toast.error('请输入用户名', {
                    position: "top-center",
                    autoClose: 2000,
                    theme: 'colored',
                });
                return;
            }

            if (!formData.password) {
                toast.error('请输入密码', {
                    position: "top-center",
                    autoClose: 2000,
                    theme: 'colored',
                });
                return;
            }
            console.log('账号密码登录数据:', formData);

            // 调用传入的登录方法
            const success = await login({
                username: formData.username,
                password: formData.password
            });

            // 登录成功
            if (success) {
                toast.success('登录成功！', {
                    position: "top-center",
                    autoClose: 1500,
                    theme: 'colored',
                    style: {
                        backgroundColor: '#4CAF50',
                        color: 'white',
                        borderRadius: '8px',
                        boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
                    },
                });
                onClose();
                onLoginSuccess?.();
            }
        } catch (error) {
            console.error('登录失败:', error);
            toast.error('登录失败，请检查账号密码', {
                position: "top-center",
                autoClose: 2000,
                theme: 'colored',
            });
        }
    };

    // 处理手机号验证码登录提交
    const handlePhoneLogin = async (e: React.FormEvent) => {
        e.preventDefault();

        try {
            // 简单验证
            if (!formData.phone) {
                toast.error('请输入手机号', {
                    position: "top-center",
                    autoClose: 2000,
                    theme: 'colored',
                });
                return;
            }

            if (!formData.code) {
                toast.error('请输入验证码', {
                    position: "top-center",
                    autoClose: 2000,
                    theme: 'colored',
                });
                return;
            }

            console.log('手机号登录数据:', formData);

            // 调用传入的手机登录方法
            const success = await phoneLogin({
                phone: formData.phone,
                code: formData.code
            });

            if (success) {
                toast.success('登录成功！', {
                    position: "top-center",
                    autoClose: 1500,
                    theme: 'colored',
                    style: {
                        backgroundColor: '#4CAF50',
                        color: 'white',
                        borderRadius: '8px',
                        boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
                    },
                });
                onClose();
                onLoginSuccess?.();
            }
        } catch (error) {
            console.error('登录失败:', error);
            toast.error('登录失败，请检查验证码', {
                position: "top-center",
                autoClose: 2000,
                theme: 'colored',
            });
        }
    };

    // 处理第三方登录
    const handleThirdPartyLogin = (platform: string) => {
        // 仅作为演示
        toast.info(`${platform}登录功能演示中`, {
            position: "top-center",
            autoClose: 2000,
            theme: 'colored',
        });
    };

    // 如果弹窗不可见，不渲染内容
    if (!visible) return null;

    return (
        <div
            className="login-modal-overlay"
            onClick={onClose}
            role="dialog"
            aria-modal="true"
            aria-labelledby="login-modal-title"
        >
            <div
                className="login-modal"
                onClick={(e) => e.stopPropagation()}
            >
                <div className="modal-header">
                    <h2 id="login-modal-title">用户登录</h2>
                    <button
                        className="close-modal-btn"
                        onClick={onClose}
                        aria-label="关闭登录窗口"
                    >
                        <i className="fa fa-times"></i>
                    </button>
                </div>

                {/* 登录方式切换标签 */}
                <div className="login-tabs">
                    <button
                        className={`login-tab ${loginMethod === 'password' ? 'active' : ''}`}
                        onClick={() => toggleLoginMethod('password')}
                    >
                        账号密码登录
                    </button>
                    <button
                        className={`login-tab ${loginMethod === 'phone' ? 'active' : ''}`}
                        onClick={() => toggleLoginMethod('phone')}
                    >
                        手机号登录
                    </button>
                </div>

                {/* 账号密码登录表单 */}
                {loginMethod === 'password' && (
                    <form onSubmit={handlePasswordLogin} className="login-form">
                        <div className="form-group">
                            <label htmlFor="username">用户名</label>
                            <input
                                type="text"
                                id="username"
                                name="username"
                                title="用户名不能为空！"
                                placeholder="请输入用户名"
                                className="form-control"
                                value={formData.username}
                                onChange={handleInputChange}
                            />
                        </div>

                        <div className="form-group">
                            <label htmlFor="password">密码</label>
                            <input
                                type="password"
                                id="password"
                                name="password"
                                title="密码不能为空！"
                                placeholder="请输入密码"
                                className="form-control"
                                value={formData.password}
                                onChange={handleInputChange}
                            />
                        </div>

                        <div className="form-options">
                            <label className="remember-me">
                                <input
                                    type="checkbox"
                                    name="remember"
                                    checked={formData.remember}
                                    onChange={handleInputChange}
                                />
                                记住我
                            </label>
                            <Link href="#" className="forgot-password">
                                忘记密码?
                            </Link>
                        </div>

                        <button type="submit" className="login-btn primary">
                            登录
                        </button>
                    </form>
                )}

                {/* 手机号验证码登录表单 */}
                {loginMethod === 'phone' && (
                    <form onSubmit={handlePhoneLogin} className="login-form">
                        <div className="form-group">
                            <label htmlFor="phone">手机号</label>
                            <input
                                type="tel"
                                id="phone"
                                name="phone"
                                title="手机号不能为空！"
                                placeholder="请输入手机号"
                                className="form-control"
                                value={formData.phone}
                                onChange={handleInputChange}
                                maxLength={11}
                            />
                        </div>

                        <div className="form-group form-code-group">
                            <label htmlFor="code">验证码</label>
                            <div className="code-input-container">
                                <input
                                    type="text"
                                    id="code"
                                    name="code"
                                    title="验证码不能为空！"
                                    placeholder="请输入验证码"
                                    className="form-control code-input"
                                    value={formData.code}
                                    onChange={handleInputChange}
                                    maxLength={6}
                                />
                                <button
                                    type="button"
                                    className="get-code-btn"
                                    onClick={getVerificationCode}
                                    disabled={countdown > 0}
                                >
                                    {countdown > 0 ? `${countdown}s后重新获取` : '获取验证码'}
                                </button>
                            </div>
                        </div>

                        <div className={'serve-item'}>
                            <label className="remember-me">
                                <input
                                    type="checkbox"
                                    name="agreeTerms"
                                    checked={formData.agreeTerms}
                                    onChange={handleInputChange}
                                />
                                我已阅读并同意<Link href="#">服务条款</Link>和<Link href="#">隐私协议</Link>
                            </label>
                        </div>

                        <button type="submit" className="login-btn primary" disabled={!formData.agreeTerms}>
                            登录
                        </button>
                    </form>
                )}

                {/* 其他登录方式 */}
                <div className="other-login-methods">
                    <div className="login-divider">
                        <span>其他登录方式</span>
                    </div>

                    <div className="social-login-buttons">
                        <button
                            type="button"
                            className="social-login-btn wechat"
                            onClick={() => handleThirdPartyLogin('微信')}
                            aria-label="微信登录"
                        >
                            <i className="fa fa-weixin"></i>
                        </button>

                        <button
                            type="button"
                            className="social-login-btn qq"
                            onClick={() => handleThirdPartyLogin('QQ')}
                            aria-label="QQ登录"
                        >
                            <i className="fa fa-qq"></i>
                        </button>
                    </div>
                </div>

                <div className="register-redirect">
                    还没有账号? <Link href="/register" onClick={onClose}>立即注册</Link>
                </div>
            </div>
        </div>
    );
}
